<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Models\Menu;
use App\Models\FunctionModel;
use App\Models\PermissionNode;
use App\Models\Role;

class MenuSystemSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 创建或更新基础菜单
        $menus = [
            [
                'code' => 'user_management',
                'name' => '用户管理',
                'path' => '/user',
                'component' => 'UserManagement',
                'icon' => 'user',
                'description' => '管理系统用户账户',
                'sort_order' => 1
            ],
            [
                'code' => 'role_management',
                'name' => '角色管理',
                'path' => '/role',
                'component' => 'RoleManagement',
                'icon' => 'team',
                'description' => '管理系统角色和权限',
                'sort_order' => 2
            ],
            [
                'code' => 'permission_management',
                'name' => '权限管理',
                'path' => '/permission',
                'component' => 'PermissionManagement',
                'icon' => 'lock',
                'description' => '管理系统权限节点',
                'sort_order' => 3
            ],
            [
                'code' => 'menu_management',
                'name' => '菜单管理',
                'path' => '/menu',
                'component' => 'MenuManagement',
                'icon' => 'bars',
                'description' => '管理系统菜单结构',
                'sort_order' => 4
            ],
            [
                'code' => 'employee_management',
                'name' => '员工管理',
                'path' => '/employee',
                'component' => 'EmployeeManagement',
                'icon' => 'idcard',
                'description' => '管理员工基础信息',
                'sort_order' => 5
            ],
            [
                'code' => 'department_management',
                'name' => '组织架构',
                'path' => '/department',
                'component' => 'DepartmentManagement',
                'icon' => 'apartment',
                'description' => '管理部门和岗位',
                'sort_order' => 6
            ]
        ];

        foreach ($menus as $menuData) {
            Menu::updateOrCreate(
                ['code' => $menuData['code']], // 查找条件
                $menuData // 更新或创建数据
            );
        }

        // 创建权限节点
        $permissionNodes = [
            // 用户管理权限节点
            ['code' => 'user_management.list.view', 'name' => '查看用户列表', 'type' => 'api', 'resource' => 'GET /api/users', 'description' => '查看用户列表数据'],
            ['code' => 'user_management.list.search', 'name' => '搜索用户', 'type' => 'api', 'resource' => 'GET /api/users?search=*', 'description' => '搜索用户功能'],
            ['code' => 'user_management.create.form', 'name' => '用户创建表单', 'type' => 'page', 'resource' => 'user-create-form', 'description' => '显示用户创建表单'],
            ['code' => 'user_management.create.submit', 'name' => '提交创建用户', 'type' => 'api', 'resource' => 'POST /api/users', 'description' => '提交创建用户请求'],
            ['code' => 'user_management.edit.form', 'name' => '用户编辑表单', 'type' => 'page', 'resource' => 'user-edit-form', 'description' => '显示用户编辑表单'],
            ['code' => 'user_management.edit.submit', 'name' => '提交编辑用户', 'type' => 'api', 'resource' => 'PUT /api/users/{id}', 'description' => '提交编辑用户请求'],
            ['code' => 'user_management.delete.confirm', 'name' => '删除用户确认', 'type' => 'page', 'resource' => 'user-delete-confirm', 'description' => '显示删除用户确认对话框'],
            ['code' => 'user_management.delete.execute', 'name' => '执行删除用户', 'type' => 'api', 'resource' => 'DELETE /api/users/{id}', 'description' => '执行删除用户操作'],
            ['code' => 'user_management.role_assign.view', 'name' => '用户角色分配界面', 'type' => 'page', 'resource' => 'user-role-assign', 'description' => '显示用户角色分配界面'],
            ['code' => 'user_management.role_assign.submit', 'name' => '提交用户角色分配', 'type' => 'api', 'resource' => 'PUT /api/users/{id}/roles', 'description' => '提交用户角色分配请求'],

            // 角色管理权限节点
            ['code' => 'role_management.list.view', 'name' => '查看角色列表', 'type' => 'api', 'resource' => 'GET /api/roles', 'description' => '查看角色列表数据'],
            ['code' => 'role_management.list.search', 'name' => '搜索角色', 'type' => 'api', 'resource' => 'GET /api/roles/search', 'description' => '搜索角色功能'],
            ['code' => 'role_management.create.form', 'name' => '角色创建表单', 'type' => 'page', 'resource' => 'role-create-form', 'description' => '显示角色创建表单'],
            ['code' => 'role_management.create.submit', 'name' => '提交创建角色', 'type' => 'api', 'resource' => 'POST /api/roles', 'description' => '提交创建角色请求'],
            ['code' => 'role_management.edit.form', 'name' => '角色编辑表单', 'type' => 'page', 'resource' => 'role-edit-form', 'description' => '显示角色编辑表单'],
            ['code' => 'role_management.edit.submit', 'name' => '提交编辑角色', 'type' => 'api', 'resource' => 'PUT /api/roles/{id}', 'description' => '提交编辑角色请求'],
            ['code' => 'role_management.delete.confirm', 'name' => '删除角色确认', 'type' => 'page', 'resource' => 'role-delete-confirm', 'description' => '显示删除角色确认对话框'],
            ['code' => 'role_management.delete.execute', 'name' => '执行删除角色', 'type' => 'api', 'resource' => 'DELETE /api/roles/{id}', 'description' => '执行删除角色操作'],

            // 权限管理权限节点
            ['code' => 'permission_management.list.view', 'name' => '查看权限节点列表', 'type' => 'api', 'resource' => 'GET /api/permissions', 'description' => '查看权限节点列表数据'],
            ['code' => 'permission_management.list.search', 'name' => '搜索权限节点', 'type' => 'api', 'resource' => 'GET /api/permissions/search', 'description' => '搜索权限节点功能'],
            ['code' => 'permission_management.create.form', 'name' => '权限节点创建表单', 'type' => 'page', 'resource' => 'permission-create-form', 'description' => '显示权限节点创建表单'],
            ['code' => 'permission_management.create.submit', 'name' => '提交创建权限节点', 'type' => 'api', 'resource' => 'POST /api/permissions', 'description' => '提交创建权限节点请求'],
            ['code' => 'permission_management.edit.form', 'name' => '权限节点编辑表单', 'type' => 'page', 'resource' => 'permission-edit-form', 'description' => '显示权限节点编辑表单'],
            ['code' => 'permission_management.edit.submit', 'name' => '提交编辑权限节点', 'type' => 'api', 'resource' => 'PUT /api/permissions/{id}', 'description' => '提交编辑权限节点请求'],
            ['code' => 'permission_management.delete.confirm', 'name' => '删除权限节点确认', 'type' => 'page', 'resource' => 'permission-delete-confirm', 'description' => '显示删除权限节点确认对话框'],
            ['code' => 'permission_management.delete.execute', 'name' => '执行删除权限节点', 'type' => 'api', 'resource' => 'DELETE /api/permissions/{id}', 'description' => '执行删除权限节点操作'],

            // 菜单管理权限节点
            ['code' => 'menu_management.list.view', 'name' => '查看菜单列表', 'type' => 'api', 'resource' => 'GET /api/menus', 'description' => '查看菜单列表数据'],
            ['code' => 'menu_management.list.search', 'name' => '搜索菜单', 'type' => 'api', 'resource' => 'GET /api/menus/search', 'description' => '搜索菜单功能'],
            ['code' => 'menu_management.create.form', 'name' => '菜单创建表单', 'type' => 'page', 'resource' => 'menu-create-form', 'description' => '显示菜单创建表单'],
            ['code' => 'menu_management.create.submit', 'name' => '提交创建菜单', 'type' => 'api', 'resource' => 'POST /api/menus', 'description' => '提交创建菜单请求'],
            ['code' => 'menu_management.edit.form', 'name' => '菜单编辑表单', 'type' => 'page', 'resource' => 'menu-edit-form', 'description' => '显示菜单编辑表单'],
            ['code' => 'menu_management.edit.submit', 'name' => '提交编辑菜单', 'type' => 'api', 'resource' => 'PUT /api/menus/{id}', 'description' => '提交编辑菜单请求'],
            ['code' => 'menu_management.delete.confirm', 'name' => '删除菜单确认', 'type' => 'page', 'resource' => 'menu-delete-confirm', 'description' => '显示删除菜单确认对话框'],
            ['code' => 'menu_management.delete.execute', 'name' => '执行删除菜单', 'type' => 'api', 'resource' => 'DELETE /api/menus/{id}', 'description' => '执行删除菜单操作'],
        ];

        foreach ($permissionNodes as $node) {
            PermissionNode::updateOrCreate(
                ['code' => $node['code']], // 查找条件
                $node // 更新或创建数据
            );
        }

        // 创建功能
        $this->createFunctions();

        // 为超级管理员角色分配所有权限
        $this->assignSuperAdminPermissions();
    }

    /**
     * 创建功能
     */
    private function createFunctions(): void
    {
        $userMenu = Menu::where('code', 'user_management')->first();
        $roleMenu = Menu::where('code', 'role_management')->first();
        $permissionMenu = Menu::where('code', 'permission_management')->first();
        $menuMenu = Menu::where('code', 'menu_management')->first();

        $functions = [
            // 用户管理功能
            [
                'code' => 'user_management.list',
                'name' => '用户列表显示',
                'level' => 'core',
                'menu_id' => $userMenu->id,
                'description' => '查看用户列表',
                'dependencies' => null,
                'sort_order' => 1
            ],
            [
                'code' => 'user_management.create',
                'name' => '创建用户',
                'level' => 'optional',
                'menu_id' => $userMenu->id,
                'description' => '创建新用户',
                'dependencies' => json_encode([$this->getFunctionId('user_management.list'), $this->getFunctionId('role_management.list')]),
                'sort_order' => 2
            ],
            [
                'code' => 'user_management.edit',
                'name' => '编辑用户',
                'level' => 'optional',
                'menu_id' => $userMenu->id,
                'description' => '编辑用户信息',
                'dependencies' => json_encode([$this->getFunctionId('user_management.list'), $this->getFunctionId('role_management.list')]),
                'sort_order' => 3
            ],
            [
                'code' => 'user_management.delete',
                'name' => '删除用户',
                'level' => 'optional',
                'menu_id' => $userMenu->id,
                'description' => '删除用户',
                'dependencies' => json_encode([$this->getFunctionId('user_management.list')]),
                'sort_order' => 4
            ],
            [
                'code' => 'user_management.role_assign',
                'name' => '用户角色分配',
                'level' => 'optional',
                'menu_id' => $userMenu->id,
                'description' => '管理用户角色关联',
                'dependencies' => json_encode([$this->getFunctionId('user_management.list'), $this->getFunctionId('role_management.list')]),
                'sort_order' => 5
            ],

            // 角色管理功能
            [
                'code' => 'role_management.list',
                'name' => '角色列表显示',
                'level' => 'core',
                'menu_id' => $roleMenu->id,
                'description' => '查看角色列表',
                'dependencies' => null,
                'sort_order' => 1
            ],
            [
                'code' => 'role_management.create',
                'name' => '创建角色',
                'level' => 'optional',
                'menu_id' => $roleMenu->id,
                'description' => '创建新角色',
                'dependencies' => json_encode([$this->getFunctionId('role_management.list')]),
                'sort_order' => 2
            ],
            [
                'code' => 'role_management.edit',
                'name' => '编辑角色',
                'level' => 'optional',
                'menu_id' => $roleMenu->id,
                'description' => '编辑角色信息',
                'dependencies' => json_encode([$this->getFunctionId('role_management.list')]),
                'sort_order' => 3
            ],
            [
                'code' => 'role_management.delete',
                'name' => '删除角色',
                'level' => 'optional',
                'menu_id' => $roleMenu->id,
                'description' => '删除角色',
                'dependencies' => json_encode([$this->getFunctionId('role_management.list')]),
                'sort_order' => 4
            ],

            // 权限管理功能
            [
                'code' => 'permission_management.list',
                'name' => '权限节点列表',
                'level' => 'core',
                'menu_id' => $permissionMenu->id,
                'description' => '查看权限节点列表',
                'dependencies' => null,
                'sort_order' => 1
            ],
            [
                'code' => 'permission_management.create',
                'name' => '创建权限节点',
                'level' => 'optional',
                'menu_id' => $permissionMenu->id,
                'description' => '创建新的权限节点',
                'dependencies' => json_encode([$this->getFunctionId('permission_management.list')]),
                'sort_order' => 2
            ],
            [
                'code' => 'permission_management.edit',
                'name' => '编辑权限节点',
                'level' => 'optional',
                'menu_id' => $permissionMenu->id,
                'description' => '编辑权限节点信息',
                'dependencies' => json_encode([$this->getFunctionId('permission_management.list')]),
                'sort_order' => 3
            ],
            [
                'code' => 'permission_management.delete',
                'name' => '删除权限节点',
                'level' => 'optional',
                'menu_id' => $permissionMenu->id,
                'description' => '删除权限节点',
                'dependencies' => json_encode([$this->getFunctionId('permission_management.list')]),
                'sort_order' => 4
            ],

            // 菜单管理功能
            [
                'code' => 'menu_management.list',
                'name' => '菜单列表',
                'level' => 'core',
                'menu_id' => $menuMenu->id,
                'description' => '查看菜单列表',
                'dependencies' => null,
                'sort_order' => 1
            ],
            [
                'code' => 'menu_management.create',
                'name' => '创建菜单',
                'level' => 'optional',
                'menu_id' => $menuMenu->id,
                'description' => '创建新菜单项',
                'dependencies' => json_encode([$this->getFunctionId('menu_management.list')]),
                'sort_order' => 2
            ],
            [
                'code' => 'menu_management.edit',
                'name' => '编辑菜单',
                'level' => 'optional',
                'menu_id' => $menuMenu->id,
                'description' => '编辑菜单信息',
                'dependencies' => json_encode([$this->getFunctionId('menu_management.list')]),
                'sort_order' => 3
            ],
            [
                'code' => 'menu_management.delete',
                'name' => '删除菜单',
                'level' => 'optional',
                'menu_id' => $menuMenu->id,
                'description' => '删除菜单项',
                'dependencies' => json_encode([$this->getFunctionId('menu_management.list')]),
                'sort_order' => 4
            ]
        ];

        foreach ($functions as $function) {
            $createdFunction = FunctionModel::updateOrCreate(
                ['code' => $function['code']], // 查找条件
                $function // 更新或创建数据
            );

            // 关联权限节点
            $this->associatePermissions($createdFunction);
        }
    }

    /**
     * 获取功能ID
     */
    private function getFunctionId(string $code): int
    {
        static $functionIds = [];

        if (!isset($functionIds[$code])) {
            $function = FunctionModel::where('code', $code)->first();
            $functionIds[$code] = $function ? $function->id : 0;
        }

        return $functionIds[$code];
    }

    /**
     * 关联功能权限节点
     */
    private function associatePermissions(FunctionModel $function): void
    {
        $permissionMappings = [
            'user_management.list' => ['user_management.list.view', 'user_management.list.search'],
            'user_management.create' => ['user_management.create.form', 'user_management.create.submit'],
            'user_management.edit' => ['user_management.edit.form', 'user_management.edit.submit'],
            'user_management.delete' => ['user_management.delete.confirm', 'user_management.delete.execute'],
            'user_management.role_assign' => ['user_management.role_assign.view', 'user_management.role_assign.submit'],
            'role_management.list' => ['role_management.list.view', 'role_management.list.search'],
            'role_management.create' => ['role_management.create.form', 'role_management.create.submit'],
            'role_management.edit' => ['role_management.edit.form', 'role_management.edit.submit'],
            'role_management.delete' => ['role_management.delete.confirm', 'role_management.delete.execute'],
            'permission_management.list' => ['permission_management.list.view', 'permission_management.list.search'],
            'permission_management.create' => ['permission_management.create.form', 'permission_management.create.submit'],
            'permission_management.edit' => ['permission_management.edit.form', 'permission_management.edit.submit'],
            'permission_management.delete' => ['permission_management.delete.confirm', 'permission_management.delete.execute'],
            'menu_management.list' => ['menu_management.list.view', 'menu_management.list.search'],
            'menu_management.create' => ['menu_management.create.form', 'menu_management.create.submit'],
            'menu_management.edit' => ['menu_management.edit.form', 'menu_management.edit.submit'],
            'menu_management.delete' => ['menu_management.delete.confirm', 'menu_management.delete.execute'],
        ];

        if (isset($permissionMappings[$function->code])) {
            foreach ($permissionMappings[$function->code] as $permissionCode) {
                $permissionNode = PermissionNode::where('code', $permissionCode)->first();
                if ($permissionNode) {
                    DB::table('function_permissions')->updateOrInsert(
                        [
                            'function_id' => $function->id,
                            'permission_node_id' => $permissionNode->id
                        ],
                        [
                            'created_at' => now(),
                            'updated_at' => now()
                        ]
                    );
                }
            }
        }
    }

    /**
     * 为超级管理员分配所有权限
     */
    private function assignSuperAdminPermissions(): void
    {
        $superAdminRole = Role::where('code', 'super_admin')->first();
        if (!$superAdminRole) {
            return;
        }

        $functions = FunctionModel::all();
        foreach ($functions as $function) {
            DB::table('role_function_permissions')->updateOrInsert(
                [
                    'role_id' => $superAdminRole->id,
                    'function_id' => $function->id
                ],
                [
                    'auto_granted' => true,
                    'granted_by' => 1, // 系统管理员
                    'granted_at' => now(),
                    'created_at' => now(),
                    'updated_at' => now()
                ]
            );
        }
    }
}
